import {createWebHistory, createRouter} from "vue-router"

const routes = [
    {
        path: '/login',
        name: "login",
        component: () => import("../page/login/Login.vue")
    },
    {
        path: "/",
        name: 'Layout',
        component: () => import("../page/MainLayout.vue"),
        // 嵌套路由
        children: [
            {
                // 这里不设置值，是把main作为默认页面
                path: "",
                redirect: '/home'
            },
            {
                // 这里不设置值，是把main作为默认页面
                path: "home",
                name: "Main",
                component: () => import("../page/Main.vue"),
            },
            // 小区管理
            {
                path: "property/community",
                name: "CommunityList",
                component: () => import("../page/property/community/CommunityList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_COMMUNITY"
                }
            },
            {
                path: "property/community/add",
                name: "CommunityAdd",
                component: () => import("../page/property/community/CommunityAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_COMMUNITY"
                }
            },
            // 房产管理
            {
                path: "property/building",
                name: "BuildingList",
                component: () => import("../page/property/building/BuildingList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_BUILDING"
                }
            },
            {
                path: "property/building/add",
                name: "BuildingAdd",
                component: () => import("../page/property/building/BuildingAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_BUILDING"
                }
            },
            {
                path: "property/home",
                name: "HomeList",
                component: () => import("../page/property/building/HomeList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_HOUSE"
                }
            },
            {
                path: "property/home/add",
                name: "HomeAdd",
                component: () => import("../page/property/building/HomeAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_HOUSE"
                }
            },
            // 停车位管理
            {
                path: "property/parking",
                name: "ParkingList",
                component: () => import("../page/property/parking/ParkingList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_PARKING"
                }
            },
            {
                path: "property/parking/add",
                name: "ParkingAdd",
                component: () => import("../page/property/parking/ParkingAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_PARKING"
                }
            },
            {
                path: "property/parking/usage",
                name: "ParkingUsageList",
                component: () => import("../page/property/parking/ParkingUsageList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_PARKING_USAGE"
                }
            },
            {
                path: "property/parking/usage/add",
                name: "ParkingUsageAdd",
                component: () => import("../page/property/parking/ParkingUsageAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_PARKING_USAGE"
                }
            },
            // 服务管理
            {
                path: "property/service/activity",
                name: "ActivityList",
                component: () => import("../page/property/service/activity/ActivityList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_ACTIVITY"
                }
            },
            {
                path: "property/service/activity/add",
                name: "ActivityAdd",
                component: () => import("../page/property/service/activity/ActivityAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_ACTIVITY"
                }
            },
            {
                path: "property/service/repair",
                name: "RepairList",
                component: () => import("../page/property/service/repair/RepairList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_REPAIR"
                }
            },
            {
                path: "property/service/repair/add",
                name: "RepairAdd",
                component: () => import("../page/property/service/repair/RepairAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_REPAIR"
                }
            },
            {
                path: "property/service/complaint",
                name: "ComplaintList",
                component: () => import("../page/property/service/complaint/ComplaintList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_COMPLAINT"
                }
            },
            {
                path: "property/service/complaint/add",
                name: "ComplaintAdd",
                component: () => import("../page/property/service/complaint/ComplaintAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_COMPLAINT"
                }
            },
            {
                path: "property/service/mailbox",
                name: "MailboxList",
                component: () => import("../page/property/service/mailbox/MailboxList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_MAILBOX"
                }
            },
            {
                path: "property/service/mailbox/add",
                name: "MailboxAdd",
                component: () => import("../page/property/service/mailbox/MailboxAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_MAILBOX"
                }
            },
            {
                path: "property/service/mailbox/reply",
                name: "MailboxReply",
                component: () => import("../page/property/service/mailbox/MailboxAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_MAILBOX"
                }
            },
            // 人员管理
            {
                path: "property/personnel/owner",
                name: "OwnerList",
                component: () => import("../page/property/personnel/owner/OwnerList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_OWNER"
                }
            },
            {
                path: "property/personnel/owner/add",
                name: "OwnerAdd",
                component: () => import("../page/property/personnel/owner/OwnerAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_OWNER"
                }
            },
            {
                path: "property/personnel/vehicle",
                name: "VehicleList",
                component: () => import("../page/property/personnel/vehicle/VehicleList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "VIEW_VEHICLE"
                }
            },
            {
                path: "property/personnel/vehicle/add",
                name: "VehicleAdd",
                component: () => import("../page/property/personnel/vehicle/VehicleAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_VEHICLE"
                }
            },
            // 系统管理
            {
                path: "system/user",
                name: "UserList",
                component: () => import("../page/system/user/UserList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_USERS"
                }
            },
            {
                path: "system/user/add",
                name: "UserAdd",
                component: () => import("../page/system/user/UserAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_USERS"
                }
            },
            {
                path: "system/role",
                name: "RoleList",
                component: () => import("../page/system/role/RoleList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_ROLES"
                }
            },
            {
                path: "system/role/add",
                name: "RoleAdd",
                component: () => import("../page/system/role/RoleAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_ROLES"
                }
            },
            {
                path: "system/permission",
                name: "PermissionList",
                component: () => import("../page/system/permission/PermissionList.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_PERMISSIONS"
                }
            },
            {
                path: "system/permission/add",
                name: "PermissionAdd",
                component: () => import("../page/system/permission/PermissionAdd.vue"),
                meta: { 
                    requiresAuth: true,
                    permission: "MANAGE_PERMISSIONS"
                }
            },
        ],
    },
];

const router = createRouter({
    // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
    history: createWebHistory("/"),
    routes, // `routes: routes` 的缩写
});

//进行路由拦截：当没有登陆标识，直接打回登陆页面，如何避免退回到 登陆页呢？
router.beforeEach((to, from, next) => {
    if (to.path === "/login") {
        next();
    } else {
        // 检查路由是否需要认证
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
        
        // 获取登录状态和token
        const isLogin = localStorage.getItem('isLogin');
        const token = localStorage.getItem('token');
        
        if (requiresAuth && (!isLogin || !token)) {
            // 需要认证但未登录，跳转到登录页
            next("/login");
        } else {
            // 检查路由是否需要特定权限
            const requiresPermission = to.meta.permission;
            if (requiresPermission) {
                // 获取用户权限
                const permissionsStr = localStorage.getItem('permissions');
                if (!permissionsStr) {
                    next("/");
                    return;
                }
                
                const permissions = JSON.parse(permissionsStr);
                
                // 检查是否有权限
                if (!hasPermission(requiresPermission, permissions)) {
                    // 没有权限，跳转到首页或显示无权限页面
                    next("/");
                    return;
                }
            }
            
            // 不需要认证或已登录且有权限
            next();
        }
    }
})

// 检查是否有权限
function hasPermission(permission, permissions) {
    if (!permission || !permissions) {
        return true;
    }
    
    // 如果是admin用户，直接返回true
    const userRoles = JSON.parse(localStorage.getItem('userRoles') || '[]');
    if (userRoles.includes('ROLE_ADMIN')) {
        return true;
    }
    
    // 检查权限数组中是否包含该权限
    if (permissions.includes(permission)) {
        return true;
    }
    
    // 检查通配符权限
    for (const p of permissions) {
        if (p.endsWith('*')) {
            const prefix = p.slice(0, -1);
            if (permission.startsWith(prefix)) {
                return true;
            }
        }
    }
    
    return false;
}

export default router;
